package pattern2.GuardedSuspension.demo;

import com.alibaba.fastjson.JSON;

import java.util.Objects;

/**
 * @创建人 liweijia
 * @创建时间 2022/7/23
 * @描述 程序的主要用途
 */
public class Receiver extends Thread {

    /**
     * 锁
     */
    private final Object lock;

    /**
     * 消息
     */
    private Msg msg;

    Receiver(Object lock) {
        this.lock = lock;
    }


    @Override
    public void run() {
        synchronized (lock) {
            System.out.println("接收者：已经做好接收准备");
            while (Objects.isNull(msg)) {
                System.out.println("接收者：暂未接收到消息");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("接收者被打断");
                    throw new RuntimeException(e);
                }
            }
            System.out.printf("接收者：接收到消息[%s]\n", JSON.toJSONString(msg.getContent()));
            try {
                System.out.println("接收者：接收者处理消息");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("接收者：接收者处理消息完毕");
        }
    }

    /**
     * 设置消息
     *
     * @param msg
     */
    public void setMsg(Msg msg) {
        this.msg = msg;
    }
}
